package org.example.stringDemo;


import java.util.Date;

/**
 * 字符串一般操作演示
 */
public class genDemo {
    public static void main(String[] args) {
        stringComp();
        stringPlus();
        cover2Int();
        stringLength();
        stringSubString();
        stringSplit();
        stringBig();
    }

    /**
     * 字符串相加
     */
    private static void stringComp() {
        String numString = "hello";
        String numString2 = "hello";
        System.out.println("字符串比较:" + (numString == "hello"));
        System.out.println("字符串比较:" + numString.equals(numString2));

    }

    /**
     * 字符串相加
     */
    private static void stringPlus() {
        String numString = "1000";
        String numString2 = "2000";
        System.out.print("字符串相加结果:");
        System.out.println(numString + numString2);
    }

    /**
     * 字符串转换为整数类型相加
     */
    private static void cover2Int() {
        String numString = "1000";
        String numString2 = "2000";
        // 转换为int类型
        int a = Integer.valueOf(numString);
        int b = Integer.valueOf(numString2);

        System.out.print("转换为int相加结果:");
        System.out.println(a + b);
    }

    /**
     * 获取字符串长度
     */
    private static void stringLength() {
        String str = "Hello world";

        System.out.print("字符串长度:");
        // 通过length()方法获取长度
        System.out.println(str.length());
    }

    /**
     * 截取子字符串
     */
    private static void stringSubString() {
        String str = "Hello world";

        System.out.print("取出的部分字符:");

        System.out.println(str.substring(5));
    }

    /**
     * 字符串拆分
     */
    private static void stringSplit() {
        String str = "Hello,world,one";

        // 通过逗号切分字符串为一个字符类型数组
        String[] array = str.split(",");

        System.out.println("拆分后的数组元素:");
        for (String s : array) {
            System.out.println(s);
        }

    }

    /**
     * 大字符拼接
     */
    private static void stringBig() {

        long start=new Date().getTime();
        String str = "";
        for (int i = 0; i < 10000; i++) {
            str += "hello,";
        }
        System.out.println("拼接后:" + str);
        System.out.println("直接拼接耗时:" + (new Date().getTime()-start));

        start=new Date().getTime();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 10000; i++) {
            sb.append("hello,");
        }
        System.out.println("拼接后:" + sb.toString());
        System.out.println("StringBuilder拼接耗时:" + (new Date().getTime()-start));
    }
}
